package cytargetlinker.conversion;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;

import org.apache.commons.io.IOUtils;

import cytargetlinker.conversion.ArgsParser.AFilesOut;
import cytargetlinker.conversion.ArgsParser.AHelp;
import cytargetlinker.conversion.ArgsParser.GraphBuilder;
import cytargetlinker.conversion.graph.Graph;
import cytargetlinker.conversion.graph.Graph.Edge;
import cytargetlinker.conversion.graph.Graph.Node;

/**
 * Import transcription factor targets from the TFe wiki.
 * @author thomas
 */
public class TFe {
	private final static Logger log = Logger.getLogger(TFe.class.getName());

	private static final String TFE_URL = "http://www.cisreg.ca/cgi-bin/tfe/api.pl?";
	
	public static Graph importTFe(String species) throws MalformedURLException, IOException {
		Graph graph = new Graph();
		graph.setTitle("TFe");
		graph.setAttribute(CommonAttributes.DATABASE.getName(), "TFe");
		graph.setAttribute(CommonAttributes.SOURCE_FILE.getName(), TFE_URL);
		graph.setAttribute(CommonAttributes.TYPE.getName(), "TF targets");
		graph.setAttribute(CommonAttributes.TARGET_ID_ATTRIBUTE.getName(), "EntrezId");
		graph.setAttribute(CommonAttributes.TARGET_DATASOURCE.getName(), "Entrez Gene");
		graph.setAttribute(CommonAttributes.SOURCE_ID_ATTRIBUTE.getName(), "EntrezId");
		graph.setAttribute(CommonAttributes.SOURCE_DATASOURCE.getName(), "Entrez Gene");
		graph.setAttribute(CommonAttributes.SOURCE_TYPE.getName(), "gene");
		graph.setAttribute(CommonAttributes.TARGET_TYPE.getName(), "gene");
		
		//First get all TF ids
		String[] tfIds = readURL(TFE_URL + "code=all-tfids").split("\n");
		for(String id : tfIds) {
			log.info("Processing " + id);
			if(species != null) {
				String tfSpecies = readURL(TFE_URL + "tfid=" + id + "&code=species").trim();
				log.info(tfSpecies);
				if(!species.equals(tfSpecies)) continue;
			}
			
			log.info("Querying info for " + id);
			String tfId = readURL(TFE_URL + "tfid=" + id + "&code=entrez-gene-id").trim();
			
			Node nSrc = graph.addNode(tfId);
			nSrc.setAttribute("Label", readURL(TFE_URL + "tfid=" + id + "&code=symbol").trim());
			nSrc.setAttribute("EntrezId", tfId);
			
			//Get targets
			String[] lines = readURL(TFE_URL + "tfid=" + id + "&code=targets").split("\n");
			for(String l : lines) {
				if("".equals(l)) continue;
				String[] cols = l.split("\t");
				for(int i = 0; i < cols.length; i++) cols[i] = cols[i].trim();
				
				String targetId = cols[0];
				
				Node nTgt = graph.addNode(targetId);
				nTgt.setAttribute("Label", cols[1]);
				nTgt.setAttribute("EntrezId", targetId);
				nTgt.appendAttribute("TFeActingComplex", cols[2]);
				
				Edge edge = graph.addEdge(nSrc + "target" + nTgt, nSrc, nTgt);
				nTgt.setAttribute("TFeActingComplex", cols[2]);
				edge.setAttribute("TFeEffect", cols[3]);
				edge.setAttribute("PMID", cols[4]);
				edge.setAttribute("TFeSource", cols[5]);
				edge.setAttribute("Interaction", "TF target");
				edge.setAttribute("Directed", "true");
			}
		}
		
		return graph;
	}
	
	private static String readURL(String url) throws MalformedURLException, IOException {
		return IOUtils.toString(new URL(url).openStream());
	}
	
	public static void main(String[] args) {
		try {
			Args pargs = ArgsParser.parse(args, Args.class);

			ArgsParser.convertAndWrite(null, pargs, new GraphBuilder() {
				public Graph buildGraph(File in) throws Exception {
					return importTFe(null);
				}
			});
		} catch(Exception e) {
			e.printStackTrace();
		}

	}

	private interface Args extends AHelp, AFilesOut { }
}
